/**
 * 部门管理
 * @constructor
 */
function Dept() {
}

Dept.init = function () {

    var options = {
        code: "dept_id",
        parentCode: "parent_id",
        uniqueId: "dept_id",
        url: "/dept/tableSearch",
        createUrl: "/add/{id}",
        updateUrl: "/edit/{id}",
        removeUrl: "/remove/{id}",
        modalName: "部门",
        columns: [{
            field: 'selectItem',
            radio: true
        },
            {
                field: 'dept_name',
                title: '部门名称',
                align: "left"
            },
            {
                field: 'leader',
                title: '负责人',
                align: "left"
            },
            {
                field: 'create_by',
                title: '创建人',
                align: "left"
            },
            {
                field: 'create_time',
                title: '创建时间',
                align: "left"
            },
            {
                title: '操作',
                align: 'left',
                formatter: function(value, row, index) {
                    if (row.parentId != 0) {
                        var actions = [];
                        actions.push("<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a> ");
                        actions.push("<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"add\")' title=\"新增\" ><i class=\"fa fa-plus\"></i>新增</a> ");
                        actions.push("<a class=\"btn btn-danger btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"del\")' title=\"删除\" ><i class=\"fa fa-trash\"></i>删除</a> ");
                        return actions.join('');
                    } else {
                        return "";
                    }
                }
            }
            ]
    };
    $.treeTable.init(options);
}
//搜索
function doSearch() {
    let params = {
        dept_name:$("#dept_name").val(),
        leader:$("#leader").val()
    }
    $.bttTable.bootstrapTreeTable('refresh', params);
}

//重置
function doRest() {
    $("#dept_name").val("");
    $("#leader").val("");
    doSearch();
}

//增加方法****************************
var Action = "";
var dept_id = 0;
var pxt = "/dept"; //控制器名称
function addRecord() {
    dept_id = 0;
    Action = "add";
    $("#myform")[0].reset();
    $("#treeId").val("");
    $("#treeName").val("");
    initTree();
}

//增加/修改数据保存****************************
function saveRecord() {
    if (!validateForm()) return false;
//创建传递的参数
    var postdata = {
        dept_id: dept_id,
        action: Action,
        parent_id: $("#treeId").val(),
        dept_name: $("#text_dept_name").val(),
        leader: $("#text_leader").val(),
    };
// console.log(JSON.stringify(postdata));
//发送异步请求到后台保存用户数据
    $.ajax({
        url: pxt + (Action == "add" ? "/save" : "/update"),
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                $.treeTable.refresh();
                swal("操作成功!", "请继续操作", "success");
            } else if(data.code === "502") {
                swal("部门已存在，操作失败!", "请重试", "error");
            } else if(data.code === "503") {
                swal("父节点不能选择自己!", "请重试", "error");
            }else if(data.code === "504") {
                swal("不能选择最后一个层级节点!", "请重试", "error");
            }else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data, type) {
    if (type == "edit") {
//修改
        dept_id = data.dept_id;
        Action = "edit";
        $("#myform")[0].reset();
        $("#save").removeAttr("disabled");
        WriteData(data)
        initTree();
        $('#myModalAdd').modal('show')
    } else if(type == "add"){
        dept_id = 0;
        Action = "add";
        $("#myform")[0].reset();
        $("#treeId").val(data.dept_id);
        $("#treeName").val(data.dept_name);
        initTree();
        $('#myModalAdd').modal('show')
    }else {
//删除
        swal({
            title: "确认是否删除",
            text: "是否确认要删除该条记录？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
//点击删除之后此处进行传递后台
            $.ajax({
                type: "delete",
                url: pxt + "/deleteById/" + data.dept_id,
                dataType: "json",
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code == "200") {
                        $.treeTable.refresh();
                        swal("删除成功!", "请继续操作", "success");
                    } else if (data.code == "501"){
                        swal("存在下级部门,不允许删除!", "请重试", "error");
                    }else if (data.code == "502"){
                        swal("部门还有关联的用户,不允许删除!", "请重试", "error");
                    }else if (data.code == "500"){
                        swal("删除失败!", "请重试", "error");
                    }
                }
            });

        });
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#treeId").val(data.parent_id);
    $("#treeName").val(data.parent_name);
    $("#text_dept_name").val(data.dept_name);
    $("#text_leader").val(data.leader);
}

//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {
            text_dept_name: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_leader: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            deptId: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            deptName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
//错误信息提示
        messages: {
            text_dept_name: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_leader: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            deptId: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: "(登录密码与确认密码不一致)"
                // number: true, //必须是数字
            },
            deptName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: "(登录密码与确认密码不一致)"
                // number: true, //必须是数字
            },
        },
    }).form();

}
function initTree() {
    var url = "/dept/treeData";
    var options = {
        id: "tree",
        treeId: "treeId",
        url: url,
        expandLevel: 2,
        onClick : zOnClick
    };
    $.tree.init(options);
}
function zOnClick(event, treeId, treeNode) {
    var treeId = treeNode.id;
    var treeName = treeNode.name;
    $("#treeId").val(treeId);
    $("#treeName").val(treeName);
}